import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../../models/comment.dart';
import '../../models/community_post.dart';
import '../../services/technique_service.dart';
import '../../services/community_service.dart';

class MyReviewsPage extends StatefulWidget {
  const MyReviewsPage({super.key});

  @override
  State<MyReviewsPage> createState() => _MyReviewsPageState();
}

class _MyReviewsPageState extends State<MyReviewsPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final TechniqueService _techniqueService = TechniqueService();
  final CommunityService _communityService = CommunityService();
  
  List<Comment> _techniqueComments = [];
  List<Comment> _postComments = [];
  bool _isLoadingTechniqueComments = false;
  bool _isLoadingPostComments = false;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _loadComments();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _loadComments() async {
    await Future.wait([
      _loadTechniqueComments(),
      _loadPostComments(),
    ]);
  }

  Future<void> _loadTechniqueComments() async {
    setState(() {
      _isLoadingTechniqueComments = true;
      _errorMessage = null;
    });

    try {
      final comments = await _techniqueService.getUserComments();
      setState(() {
        _techniqueComments = comments;
        _isLoadingTechniqueComments = false;
      });
    } catch (e) {
      setState(() {
        _isLoadingTechniqueComments = false;
        _errorMessage = '加载钓技评论失败: $e';
      });
    }
  }

  Future<void> _loadPostComments() async {
    setState(() {
      _isLoadingPostComments = true;
      _errorMessage = null;
    });

    try {
      final comments = await _communityService.getUserComments();
      setState(() {
        _postComments = comments;
        _isLoadingPostComments = false;
      });
    } catch (e) {
      setState(() {
        _isLoadingPostComments = false;
        _errorMessage = '加载帖子评论失败: $e';
      });
    }
  }

  Future<void> _deleteComment(Comment comment, bool isTechniqueComment) async {
    final bool? confirm = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这条评论吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('确定'),
          ),
        ],
      ),
    );

    if (confirm != true) return;

    try {
      if (isTechniqueComment) {
        await _techniqueService.deleteComment(comment.id.toString());
        setState(() {
          _techniqueComments.removeWhere((c) => c.id == comment.id);
        });
      } else {
        await _communityService.deleteComment(comment.id);
        setState(() {
          _postComments.removeWhere((c) => c.id == comment.id);
        });
      }
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('评论删除成功')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('删除失败: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的评论'),
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '钓技评论'),
            Tab(text: '帖子评论'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildTechniqueCommentsTab(),
          _buildPostCommentsTab(),
        ],
      ),
    );
  }

  Widget _buildTechniqueCommentsTab() {
    if (_isLoadingTechniqueComments) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, size: 64, color: Colors.grey),
            const SizedBox(height: 16),
            Text(_errorMessage!, style: const TextStyle(color: Colors.grey)),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadTechniqueComments,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_techniqueComments.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.comment_outlined, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text('暂无钓技评论', style: TextStyle(color: Colors.grey)),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _techniqueComments.length,
      itemBuilder: (context, index) {
        final comment = _techniqueComments[index];
        return _buildCommentCard(comment, true);
      },
    );
  }

  Widget _buildPostCommentsTab() {
    if (_isLoadingPostComments) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, size: 64, color: Colors.grey),
            const SizedBox(height: 16),
            Text(_errorMessage!, style: const TextStyle(color: Colors.grey)),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadPostComments,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (_postComments.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.comment_outlined, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text('暂无帖子评论', style: TextStyle(color: Colors.grey)),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _postComments.length,
      itemBuilder: (context, index) {
        final comment = _postComments[index];
        return _buildCommentCard(comment, false);
      },
    );
  }

  Widget _buildCommentCard(Comment comment, bool isTechniqueComment) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      child: InkWell(
        onTap: () {
          if (isTechniqueComment) {
            // 跳转到钓技详情页
            context.push('/technique/${comment.targetId ?? comment.techniqueId}');
          } else {
            // 跳转到社区详情页 - 需要构造CommunityPost对象
            final post = CommunityPost(
              id: comment.targetId ?? 0,
              title: comment.targetTitle ?? '未知标题',
              content: '',
              images: [],
              authorName: '',
              authorAvatar: '',
              publishTime: DateTime.now(),
              likeCount: 0,
              commentCount: 0,
              readCount: 0,
              tags: [],
              location: '',
            );
            context.push('/community/${comment.targetId}', extra: post);
          }
        },
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          isTechniqueComment ? '钓技评论' : '帖子评论',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          comment.targetTitle ?? '未知标题',
                          style: const TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
                  ),
                  PopupMenuButton<String>(
                    onSelected: (value) {
                      if (value == 'delete') {
                        _deleteComment(comment, isTechniqueComment);
                      }
                    },
                    itemBuilder: (context) => [
                      const PopupMenuItem(
                        value: 'delete',
                        child: Row(
                          children: [
                            Icon(Icons.delete, color: Colors.red),
                            SizedBox(width: 8),
                            Text('删除'),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              const SizedBox(height: 12),
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.grey[50],
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: Colors.grey[200]!),
                ),
                child: Text(
                  comment.content,
                  style: const TextStyle(fontSize: 14),
                ),
              ),
              const SizedBox(height: 12),
              Row(
                children: [
                  const Icon(Icons.access_time, size: 16, color: Colors.grey),
                  const SizedBox(width: 4),
                  Text(
                    _formatDate(comment.createTime),
                    style: TextStyle(
                      color: Colors.grey[600],
                      fontSize: 12,
                    ),
                  ),
                  const Spacer(),
                  if (comment.likeCount > 0) ...[
                    const Icon(Icons.thumb_up, size: 16, color: Colors.grey),
                    const SizedBox(width: 4),
                    Text(
                      '${comment.likeCount}',
                      style: TextStyle(
                        color: Colors.grey[600],
                        fontSize: 12,
                      ),
                    ),
                  ],
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  String _formatDate(String dateStr) {
    try {
      final date = DateTime.parse(dateStr);
      final now = DateTime.now();
      final difference = now.difference(date);

      if (difference.inDays > 0) {
        return '${difference.inDays}天前';
      } else if (difference.inHours > 0) {
        return '${difference.inHours}小时前';
      } else if (difference.inMinutes > 0) {
        return '${difference.inMinutes}分钟前';
      } else {
        return '刚刚';
      }
    } catch (e) {
      return dateStr;
    }
  }
}